package com.yuelao.yuelao_backend.controller;

import com.yuelao.yuelao_backend.common.ApiResponse;
import com.yuelao.yuelao_backend.common.BizException;
import com.yuelao.yuelao_backend.common.ErrorCode;
import com.yuelao.yuelao_backend.dto.ShopItemDTO;
import com.yuelao.yuelao_backend.dto.UserItemDTO;
import com.yuelao.yuelao_backend.dto.request.PurchaseItemRequest;
import com.yuelao.yuelao_backend.dto.request.UseItemRequest;
import com.yuelao.yuelao_backend.service.ShopService;
import com.yuelao.yuelao_backend.util.UserContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/shop")
@Slf4j
public class ShopController {

    @Resource
    private ShopService shopService;

    /**
     * 获取商城商品列表
     * GET /shop/items
     * @param category 商品类别，可选
     * @return 商品列表
     */
    @GetMapping("/items")
    public ApiResponse<List<ShopItemDTO>> getShopItems(@RequestParam(required = false) String category) {
        List<ShopItemDTO> items = shopService.getShopItems(category);
        return ApiResponse.ok(items);
    }

    /**
     * 购买商品
     * POST /shop/purchase
     * @param request 购买请求
     * @return 是否成功
     */
    @PostMapping("/purchase")
    public ApiResponse<Boolean> purchaseItem(@Valid @RequestBody PurchaseItemRequest request) {
        Long currentUserId = UserContextUtil.getCurrentUserId();
        boolean result = shopService.purchaseItem(currentUserId, request.getItemId(), request.getQuantity());
        return ApiResponse.ok(result);
    }

    /**
     * 获取用户拥有的道具列表
     * GET /shop/my-items
     * @return 道具列表
     */
    @GetMapping("/my-items")
    public ApiResponse<List<UserItemDTO>> getMyItems() {
        Long currentUserId = UserContextUtil.getCurrentUserId();
        List<UserItemDTO> myItems = shopService.getMyItems(currentUserId);
        return ApiResponse.ok(myItems);
    }

    /**
     * 使用道具
     * POST /shop/use-item
     * @param request 使用道具请求
     * @return 是否成功
     */
    @PostMapping("/use-item")
    public ApiResponse<Boolean> useItem(@Valid @RequestBody UseItemRequest request) {
        Long currentUserId = UserContextUtil.getCurrentUserId();
        boolean result = shopService.useItem(currentUserId, request.getUserItemId());
        return ApiResponse.ok(result);
    }
}